﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.Linq;

namespace Admin.cadastros
{
    public partial class listausuarios : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var situacao = new[] { new { SitCod = "A", SitNome = "Ativo" }, 
                                       new { SitCod = "I", SitNome = "Inativo" },
                                       new { SitCod = "B", SitNome = "Bloqueado"},
                                       new { SitCod = "T", SitNome = "** TODOS **"}};

                cmbSituacao.DataSource = situacao;
                cmbSituacao.DataBind();
                cmbSituacao.SelectedValue = "A";

                var cadsituacao = new[] {
                                    new { SitCod = "A", SitNome = "Ativo" }, 
                                       new { SitCod = "I", SitNome = "Inativo" },
                                       new { SitCod = "B", SitNome = "Bloqueado"},
                                       };
                cmdCadSituacao.DataSource = cadsituacao;
                cmdCadSituacao.DataBind();

                getData();

            }
            String script = @"$(document).ready(function () 
                                {  
                                    combobox();
                                    $('.botao').button();
                                    $('.botaoNovo').button({icons: {primary: 'ui-icon-plus'}});
                                    $('.botaoNovo').colorbox({inline:true, onOpen: function () { Limpa();$('#Senha').show();$('#trocaSenha').hide(); } });
                                    $('.btnSalvar').button({icons: {primary: 'ui-icon-disk'}});
                                    $('.Editar').button({icons: {primary: 'ui-icon-pencil'}});
                                    $('#VerSenha').button({icons: {primary: 'ui-icon-locked'}});
                                    //$('a.Editar').colorbox({inline:true,href:'#novo',onOpen:function(){}});
                                    //
                                   $('a.Editar').colorbox({ inline: true, href: '#novo', 
                                                            onOpen: function () { Le(this.id); }, 
                                                            onClose: function(){Limpa();} });
                                    
                                });
                                function Salva() {
                                    document.getElementById('login').value = document.getElementById('txtLogin').value;
                                    document.getElementById('nome').value = document.getElementById('txtNome').value;
                                    document.getElementById('senha').value = document.getElementById('txtSenha').value;
                                    document.getElementById('telefone').value = document.getElementById('txtTelefone').value;
                                    document.getElementById('email').value = document.getElementById('txtEmail').value;
                                    document.getElementById('situacao').value = document.getElementById('cmdCadSituacao').value;
                                }

                                function Le(usuLogin) {
                                    $.ajax(
                                    {
                                        url: 'usuario.ashx',
                                        data: { usuLog: usuLogin },
                                        async: true,
                                        success: function (p) {
                                            //debugger;
                                            if (typeof p === 'string') {
                                                var obj = eval('(' + p + ')');
                        
                                                document.getElementById('txtLogin').value = obj.usuLogin;
                                                document.getElementById('txtNome').value = obj.usuNome.toString();
                                                document.getElementById('txtSenha').value = obj.usuSenha.toString();
                                                document.getElementById('txtConfirmPass').value = obj.usuSenha.toString();
                                                document.getElementById('txtTelefone').value = obj.usuTelefone.toString();
                                                document.getElementById('txtEmail').value = obj.usuMail.toString();
                                                document.getElementById('cmdCadSituacao').value = obj.usuSta.toString();
                                                $('#Senha').hide();
                                                $('#txtLogin').attr('disabled', true);
                                            }
                                        },
                                        error: function (p) {
                                            alert(p);
                                        }
                                    });
                                }

                                function Limpa(){
                                    $('#novo').find(':input').each(function() {
                                        switch(this.type) {
                                            case 'password':
                                            case 'select-multiple':
                                            case 'select-one':
                                            case 'text':
                                            case 'textarea':
                                                $(this).val('');
                                                break;
                                            case 'checkbox':
                                            case 'radio':
                                                this.checked = false;
                                        }
                                    });
                                    $('#txtLogin').attr('disabled', false);
                                }";


            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "javas", script, true);

        }

        private void getData()
        {
            var listaUsuarios = (from usuario in new LojaAdminDataContext().GetTable<Usuario>()
                                 where (usuario.UsuNom.Contains(txtNomPro.Text) ||
                                     String.IsNullOrEmpty(txtNomPro.Text)) &&
                                     (
                                        usuario.UsuSta.Equals(cmbSituacao.SelectedValue) ||
                                        (
                                            (String.IsNullOrEmpty(cmbSituacao.SelectedValue)) ||
                                            (cmbSituacao.SelectedValue == "T")
                                        )
                                     )
                                 select new { usuario.UsuLog, usuario.UsuNom, usuario.UsuTel, usuario.UsuMai }).ToList();
            lista.DataSource = listaUsuarios;
            lista.DataBind();

        }

        protected void btnPesquisar_Click(object sender, EventArgs e)
        {
            getData();
            txtCelular.Text = string.Empty;
            txtConfirmPass.Text = string.Empty;
            txtEmail.Text = string.Empty;
            txtLogin.Text = string.Empty;
            txtNome.Text = string.Empty;
            txtSenha.Text = string.Empty;
            txtTelefone.Text = string.Empty;
            cmdCadSituacao.SelectedItem.Value = "A";
            nome.Text = string.Empty;
            senha.Text = string.Empty;
            email.Text = string.Empty;
            telefone.Text = string.Empty;
            situacao.Text = string.Empty;
            login.Text = string.Empty;
        }

        protected void btnSalvar_Click(object sender, EventArgs e)
        {
            using (LojaAdminDataContext dc = new LojaAdminDataContext())
            {
                Table<Usuario> tblUser = dc.GetTable<Usuario>();
                Usuario user = tblUser.Where(u => u.UsuLog == login.Text).SingleOrDefault();

                if (user == null)
                {
                    user = new Usuario();
                    user.UsuLog = login.Text.Trim();
                    user.UsuNom = nome.Text.Trim();
                    Donini.Crypt.Crypt c = new Donini.Crypt.Crypt(Donini.Crypt.CryptProvider.Rijndael);
                    c.Key = "chocolate";
                    user.UsuSen = c.Encrypt(senha.Text);
                    user.UsuTel = telefone.Text;
                    user.UsuMai = email.Text;
                    user.UsuSta = Char.Parse(situacao.Text);
                    tblUser.InsertOnSubmit(user);
                }
                else
                {
                    user.UsuNom = nome.Text.Trim();
                    Donini.Crypt.Crypt c = new Donini.Crypt.Crypt(Donini.Crypt.CryptProvider.Rijndael);
                    c.Key = "chocolate";
                    user.UsuSen = c.Encrypt(senha.Text);
                    user.UsuTel = telefone.Text;
                    user.UsuMai = email.Text;
                    user.UsuSta = Char.Parse(situacao.Text);
                }

                try
                {
                    tblUser.Context.SubmitChanges();
                    ScriptManager.RegisterClientScriptBlock(btnSalvar, btnSalvar.GetType(), "fechar", "$.colorbox.close();", true);
                }
                catch (Exception error)
                {
                    throw new Exception(error.Message);
                }
            }
            getData();
        }
    }
}